﻿#include "mainwindow.h"



#define Plot2_DotColor QColor(236,110,0)
#define Plot2_LineColor QColor(246,98,0)
#define LineWidth 2
#define DotWidth 10

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

#ifdef Q_OS_WIN//如果是windows系统
    this->setWindowFlags(Qt::Dialog | Qt::WindowMinimizeButtonHint|Qt::WindowCloseButtonHint);
#else
     this->setWindowFlags(Qt::WindowMinMaxButtonsHint | Qt::FramelessWindowHint);//去窗口边框
#endif

    clientMqtt();


    dataCustomPlotInit();

    usartDataInit();

    sht20_Init();
    sgp30_init();

    show_co2_tvoc = false;
    show_temp_humi = true;
    show_pm2_5    = false;

    mainTimer  = new QTimer(this);

    /* 信号与槽函数连接 */
    connect(mainTimer, SIGNAL(timeout()), this, SLOT(read_sensor_data()));

    /* 开启定时器 */
    mainTimer->start(1000);   // 1秒更新一次


    video = new videoshow(ui->widget_2);
    video->setFixedWidth(PIXWIDTH);
    video->setFixedHeight(PIXHEIGHT);

    V4l2_T = new V4l2Thread(video);

    V4l2_T->start();

    ui->pushButton->hide();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::clientMqtt() {
    client = new QMQTT::Client(); // 初始化QMQTT客户指针

    connect(client, SIGNAL(received(QMQTT::Message)),this, SLOT(onMQTT_Received(QMQTT::Message)));
    connect(client, SIGNAL(subscribed(QString,quint8)), this, SLOT(onMQTT_subscribed(QString,quint8)) );
    connect(client, SIGNAL(unsubscribed(QString)), this, SLOT( onMQTT_unSubscribed(QString)));


//    // oneNet server //
//    QHostAddress host("183.230.40.39"); // 代理服务器 IP
//    QByteArray password = "qt_test"; // 设备名称
//    quint16 port = 6002; // 代理服务器端口
//    QString deviceId = "996501377"; // 设备 ID
//    QString productId = "543222";   // 产品 ID

//    client->setKeepAlive(120); // 心跳
//    client->setHost(host); // 设置 EMQ 代理服务器
//    client->setPort(port); // 设置 EMQ 代理服务器端口
//    client->setClientId(deviceId); // 设备 ID
//    client->setUsername(productId); // 产品 ID
//    client->setPassword(password);
//    client->cleanSession();
//    client->setVersion(QMQTT::MQTTVersion::V3_1_1); // 设置mqtt版本

    //ali_thing
    QString host("iot-06z00ac7lu605si.mqtt.iothub.aliyuncs.com"); // 代理服务器 IP
    QByteArray password = "ff4e488fd1583fc3548182fc7a553c55256d2fbecd69623d5435469421b061e4"; // 设备密码
    quint16 port = 1883; // 代理服务器端口
    QString ClientId = "h14lBOv58fr.qt_test|securemode=2,signmethod=hmacsha256,timestamp=1663913175896|"; // 设备 ID
    QString productId = "qt_test&h14lBOv58fr";   // 产品 ID

    client->setKeepAlive(120); // 心跳
    client->setHostName(host); // 设置 EMQ 代理服务器
    client->setPort(port); // 设置 EMQ 代理服务器端口
    client->setClientId(ClientId); // 设备 ID
    client->setUsername(productId); // 产品 ID
    client->setPassword(password);
    client->cleanSession();
    client->setVersion(QMQTT::MQTTVersion::V3_1_1); // 设置mqtt版本

    client->connectToHost(); // 连接 EMQ 代理服务器

    QTimer::singleShot(1000, this, [=](){
        client->subscribe("/sys/h14lBOv58fr/qt_test/thing/service/property/set",0);
    });
}

void MainWindow::onMQTT_Received(QMQTT::Message message) {
    QString str = message.payload();
    qDebug() <<"\nTopic: " << message.topic() << "payload:" <<str;
}

void MainWindow::onMQTT_subscribed(QString topic, quint8 qos) {
    qDebug() << "\n订阅topic = " << topic << "Qos = " << qos << " 成功!";
}

void MainWindow::onMQTT_unSubscribed(QString topic) {
    qDebug() << "\nonMQTT_unSubscribed:" << topic;
}


void MainWindow::on_pushButton_clicked()
{
    QString topic = "/sys/h14lBOv58fr/qt_test/thing/event/property/post";
    QString payload = "{\"method\":\"thing.event.property.post\",\"id\":\"502606429\",\"params\":{\"temperature\":51.2},\"version\":\"1.0.0\"}";

    QMQTT::Message message(1,topic,payload.toUtf8());


    client->publish(message);
}


void MainWindow::dataCustomPlotInit()
{
    QFont font;
//    font.setPointSize(12);
    /* 实例化，设置位置、背景颜色 */
    QBrush brush(QColor(50, 50, 50));
        dataCustomPlot = new QCustomPlot(ui->widget);
        dataCustomPlot->setGeometry(0, 0, 450, 400);
        dataCustomPlot->setBackground(brush);
        dataCustomPlot->installEventFilter(this);

        /* x轴、Y轴相关配置 */
        QPen pen(Qt::white);

        font.setPointSize(15);
        dataCustomPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom);      //可拖拽+可滚轮缩放
        dataCustomPlot->xAxis->setLabelColor(QColor(Qt::white)); // X轴上标识label字体颜色
        dataCustomPlot->yAxis->setLabelColor(QColor(Qt::white));
        dataCustomPlot->xAxis->setTickPen(pen);                  //  设置x轴上坐标点上对应的刻度线的颜色
        dataCustomPlot->xAxis->setTickLabelRotation(60);//设置标签角度旋转
        dataCustomPlot->yAxis->setTickPen(pen);
        dataCustomPlot->xAxis->setBasePen(pen);                  //  设置x轴 轴线本身的颜色
        dataCustomPlot->yAxis->setBasePen(pen);
        dataCustomPlot->xAxis->setTickLabelColor(QColor(Qt::white)); // 设置x轴刻度值文本的颜色
        dataCustomPlot->yAxis->setTickLabelColor(QColor(Qt::white));
        dataCustomPlot->xAxis->setSubTicks(false);  //  隐藏x轴刻度线
        dataCustomPlot->yAxis->setSubTicks(false);  //  隐藏y轴刻度线
        dataCustomPlot->xAxis->setLabelFont(font);  //  设置x轴标识label文本字体大小
        dataCustomPlot->yAxis->setLabelFont(font);  //  设置y轴标识label文本字体大小
        font.setPointSize(10);
        dataCustomPlot->xAxis->setTickLabelFont(font);
        dataCustomPlot->yAxis->setTickLabelFont(font);
        dataCustomPlot->xAxis->setLabel("时间");
        dataCustomPlot->yAxis->setLabel("温湿度");


         dataCustomPlot->legend->setVisible(true);

        /* 增加一个数据曲线 */
        pen.setColor(Qt::yellow);    // 设置画笔的颜色
        dataCustomPlot->addGraph();                // 增加曲线图
        dataCustomPlot->graph(0)->setName("温度"); // 设置曲线的名字
        dataCustomPlot->graph(0)->setPen(pen);     // 设置曲线画笔的颜色
        dataCustomPlot->graph(0)->setLineStyle(QCPGraph::lsLine); // 设置连接线的类型 两点直线连接


        dataCustomPlot->graph(0)->setScatterStyle(              //绘制打出来的点
            QCPScatterStyle(QCPScatterStyle::ssCircle,
                            QPen(Plot2_DotColor, LineWidth),
                            QBrush(Plot2_DotColor), DotWidth));

         dataCustomPlot->graph(0)->rescaleAxes(false);

        pen.setColor(Qt::red);    // 设置画笔的颜色
        dataCustomPlot->addGraph();                // 增加曲线图
        dataCustomPlot->graph(1)->setName("湿度"); // 设置曲线的名字
        dataCustomPlot->graph(1)->setPen(pen);     // 设置曲线画笔的颜色
        dataCustomPlot->graph(1)->setLineStyle(QCPGraph::lsLine); // 设置连接线的类型 两点直线连接

//        dataCustomPlot->graph(1)->setScatterStyle(              //绘制打出来的点
//            QCPScatterStyle(QCPScatterStyle::ssCircle,
//                            QPen(Plot2_DotColor, LineWidth),
//                            QBrush(Plot2_DotColor), DotWidth));

        dataCustomPlot->graph(1)->rescaleAxes(false);
}


void MainWindow::read_sensor_data()
{

    read_Sht20_data();
    myHelper::Sleep(100);
    read_sgp30_data();

    if(client->isConnectedToHost())
    {
        QString topic = "/sys/h14lBOv58fr/qt_test/thing/event/property/post";
        QString payload = "{\"method\":\"thing.event.property.post\",\"id\":\"502606429\",\"params\":{\"temperature\":"+QString::number(temp,'f',2)+",\"Humidity\":"+QString::number(humi,'f',2)+",\"co2\":"+QString::number(CO2_data)+",\"TVOC\":"+QString::number(TVOC_data)+",\"PM25\":"+QString::number(PM_2_5_data)+",\"PM10\":"+QString::number(PM10_data)+"},\"version\":\"1.0.0\"}";

        QMQTT::Message message(0,topic,payload.toUtf8());


    //

        client->publish(message);
    }





}

void MainWindow::on_comboBox_currentIndexChanged(int index)
{
    if(index == 0)
    {
        dataCustomPlot->yAxis->setLabel("温湿度");
        dataCustomPlot->graph(0)->setName("温度"); // 设置曲线的名字
        dataCustomPlot->graph(1)->setName("湿度"); // 设置曲线的名字

        dataCustomPlot->graph(0)->data().data()->clear();
        dataCustomPlot->graph(1)->data().data()->clear();

        now_time  = 0;
        show_co2_tvoc = false;
        show_temp_humi = true;
        show_pm2_5    = false;

        dataCustomPlot->replot();
    }
    else if(index == 1)
    {
         dataCustomPlot->yAxis->setLabel("TVOC+CO2");
         dataCustomPlot->graph(0)->setName("CO2"); // 设置曲线的名字
         dataCustomPlot->graph(1)->setName("TVOC"); // 设置曲线的名字

         dataCustomPlot->graph(0)->data().data()->clear();
         dataCustomPlot->graph(1)->data().data()->clear();

         now_time  = 0;
         show_co2_tvoc = true;
         show_temp_humi = false;
         show_pm2_5    = false;

         dataCustomPlot->replot();
    }
    else if(index == 2)
    {
        dataCustomPlot->yAxis->setLabel("PM2.5+PM10");
        dataCustomPlot->graph(0)->setName("PM2.5"); // 设置曲线的名字
        dataCustomPlot->graph(1)->setName("PM10"); // 设置曲线的名字

        dataCustomPlot->graph(0)->data().data()->clear();
        dataCustomPlot->graph(1)->data().data()->clear();

        now_time  = 0;

        show_pm2_5    = true;
        show_co2_tvoc = false;
        show_temp_humi = false;

        dataCustomPlot->replot();
    }
}
